package com.lmk.pet.service.Impl;

import com.lmk.basic.exception.BusinessException;
import com.lmk.basic.service.IBaiduAiAuditService;
import com.lmk.basic.service.Impl.BaseServiceImpl;
import com.lmk.basic.util.*;
import com.lmk.order.domain.OrderPetAcquisition;
import com.lmk.order.mapper.OrderPetAcquisitionMapper;
import com.lmk.org.domain.Employee;
import com.lmk.org.domain.Shop;
import com.lmk.org.mapper.EmployeeMapper;
import com.lmk.org.mapper.ShopMapper;
import com.lmk.pet.domain.Pet;
import com.lmk.pet.domain.SearchMasterMsg;
import com.lmk.pet.domain.SearchMasterMsgAuditLog;
import com.lmk.pet.mapper.PetMapper;
import com.lmk.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.lmk.pet.mapper.SearchMasterMsgMapper;
import com.lmk.pet.query.SearchMasterMsgQuery;
import com.lmk.pet.service.ISearchMasterMsgService;
import com.lmk.user.domain.Logininfo;
import com.lmk.user.domain.User;
import com.lmk.user.mapper.UserMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService iBaiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        /*
         *1.添加寻主消息到数据库
         */
        // 获取登陆人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 将userid添加到searchMasterMsg表的userId中
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        /*
         *2.审核-百度AI审核
         */
        Boolean aBoolean = iBaiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean bBoolean = iBaiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        /*
         *3.审核通过
         */
        if (aBoolean && bBoolean){
            //1.修改状态,将状态修改为1
            searchMasterMsg.setState(1);
            searchMasterMsgMapper.update(searchMasterMsg);

            //2.查询最近的店铺
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if(nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            // 更新数据库
            searchMasterMsgMapper.update(searchMasterMsg);
            //3.添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(1);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);

            if(nearestShop!=null){
                //SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
                System.out.println("您有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
            }

        }else {// 审核失败
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());

            log.setNote("审核失败，内容非法");
            log.setState(0);
            searchMasterMsgAuditLogMapper.save(log);
            //SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
            System.out.println("抱歉，您的审核未通过，请稍后再试");
            throw new BusinessException("审核失败，内容非法");
        }

    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        // 设置用户id
        query.setUserId(user.getId());
        // 调用父类分页查询
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        // 判断当前登录人是店铺管理员还是平台管理员，若是店铺管理员就要设置他的店铺id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        query.setState(1);
        // 判断
        if(employee.getShop_id() !=null ){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);

    }

    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.updateShopId(msgId);
    }

    @Override
    public void accept(Map<String, String> map) {
        //获取前端传递的参数
        long msgId = Long.parseLong(map.get("msgId"));
        long handler = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //校验当前寻主消息是否生成订单,如果有，证明店铺管理员正在完成订单
        OrderPetAcquisition order =  orderPetAcquisitionMapper.locadByMsgId(msgId);
        if(order!=null){
            throw new BusinessException("已经被接单，正在处理中！");
        }
        //2.生成宠物保存到数据库
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet =  msg2Pet(msg);
        petMapper.save(pet);
        //3.生成订单
        OrderPetAcquisition tempOrder = createOrder(msg,pet,handler,note);
        Message<OrderPetAcquisition> build = MessageBuilder.withPayload(tempOrder).build();
        //发送mq消息
        rocketMQTemplate.syncSend("order-topic"+":"+"order-tags",build,3000,18);

        orderPetAcquisitionMapper.save(tempOrder);




        //4.发送短信
       /* Employee employee = employeeMapper.loadById(handler);
        SmsUtils.sendSms(employee.getPhone(),"订单已经送达，请注意查收");*/
        System.out.println("请到【"+msg.getAddress()+"】接回宠物");
    }



    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, Pet pet, long handler, String note) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        orderPetAcquisition.setOrderSn(orderSn);
        orderPetAcquisition.setDigest(msg.getName()+"的收购订单");


        Date date = new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        orderPetAcquisition.setLastcomfirmtime(date);
        orderPetAcquisition.setState(0);
        orderPetAcquisition.setPrice(msg.getPrice());


        orderPetAcquisition.setPetId(pet.getId());

        orderPetAcquisition.setUserId(pet.getUserId());

        orderPetAcquisition.setAddress(msg.getAddress());
        orderPetAcquisition.setEmpId(handler);
        orderPetAcquisition.setSearchMasterMsgId(msg.getId());
        return orderPetAcquisition;

    }
}
